const { dialog, ipcMain, app } = require("electron");
const fs = require("fs");
const path = require("path");

const handleFileEvent = (mainWindow) => {
  //读文件，含对话框
  ipcMain.handle("on-read-file-event", (e) => {
    return new Promise((resolve, reject) => {
      // 显示文件选择对话框
      const filePaths = dialog.showOpenDialogSync(mainWindow, {
        title: "选择文件",
        buttonLabel: "打开",
        filters: [{ name: "数据文件", extensions: "json" }],
        properties: ["openFile"],
      });

      if (!filePaths) {
        reject("用户取消了文件选择");
      }

      // 处理选择的文件
      console.log(filePaths);
      filePaths.forEach((filePath) => {
        console.log(filePath); // 你可以在这里读取文件内容
        fs.readFile(filePath, "utf8", (err, data) => {
          if (err) {
            reject(err);
          }
          resolve(data); // 输出文件内容
        });
      });
    });
  });

  // 读文件，无对话框
  ipcMain.handle("on-read-file-no-dialog-event", (e, filePath) => {
    return new Promise((resolve, reject) => {
      if (!filePath) {
        reject("路径为空");
      }
      let _filePath = path.join(process.cwd(), "./hand/", filePath);
      if (!fs.existsSync(_filePath)) resolve(null);
      fs.readFile(_filePath, (err, data) => {
        if (err) {
          reject(err);
        }
        resolve(data.toString("base64")); // 输出文件内容
      });
    });
  });
};

module.exports = handleFileEvent;
